package main

import (
	"context"
	"fmt"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"golang.org/x/sync/errgroup"
	"net/http"
	"os"
	"week13/configs"
	"week13/internal/service"
	"week13/log"
)

type Server interface {
	Run(ctx context.Context) error
	Close()
}

func main()  {
	var err error
	dir := "C:\\Users\\03\\Desktop\\training-camp\\week13\\configs\\json\\app.json"
	f, err := os.Open(dir)
	if err !=nil {
		panic(err)
	}
	defer f.Close()
	appConfigs := configs.LoadAppConfigs(f)
	srvs := make([]Server,0)
	agentSrv := service.NewAgentServer(appConfigs["agent"])
	assetSrv := service.NewAssetServer(appConfigs["asset"])
	authSrv := service.NewAuthServer(appConfigs["auth"])
	adminSrv := service.NewAdminServer(appConfigs["admin"])
	prometheusSrv := NewPrometheus(appConfigs["prometheus"].Addr)
	srvs = append(srvs,agentSrv,assetSrv,authSrv,adminSrv,prometheusSrv)
	run(context.Background(),srvs...)


}
type Prometheus struct {
	Addr string
}

func (p *Prometheus) Run(ctx context.Context) error  {
	mux := http.NewServeMux()
	mux.Handle("/metrics",promhttp.Handler())
	fmt.Println("Listening Metrics...")
	server := &http.Server{
		Addr:    p.Addr,
		Handler: mux,
	}
	go func() {
		select {
		case <-ctx.Done():
			fmt.Println("close1")
			server.Shutdown(ctx)
		}
	}()
	err := server.ListenAndServe()
	return err
}
func (p *Prometheus) Close(){

}

func NewPrometheus(Addr string) *Prometheus{
	return &Prometheus{
		Addr: Addr,
	}
}
func run(ctx context.Context,srvs ...Server) {
	group := new(errgroup.Group)
	ctx, cancel := context.WithCancel(context.Background())
	for _,srv := range srvs {
		s := srv
		fun := func() error{
			return s.Run(ctx)
		}
		group.Go(fun)
	}
	if err := group.Wait(); err != nil {
		cancel()
		log.Fatal("apps  errors:", err.Error())
	}
}